import type {
  ActionType,
  ParamsType,
  ProColumns,
  RequestData,
} from '@ant-design/pro-components';
import { FooterToolbar, ProCard, ProTable } from '@ant-design/pro-components';
import { FormattedMessage,  useIntl } from '@umijs/max';
import {
  Button,
  Checkbox,
  CheckboxProps,
  Input,
  message,
  Tree,
  TreeDataNode,
  TreeProps,
} from 'antd';
import { debounce } from 'lodash';
import React, { useCallback, useEffect, useRef, useState } from 'react';

const { Search } = Input;

interface TreeTableProps<T, U> {
  treeDataSource: TreeDataNode[];
  removeRule?: (keys: T[]) => Promise<void>;
  columns: ProColumns<T>[];
  treeTitle?: string;
  checkTitle?: string;
  searchPlaceholder?: string;
  onRowClick?: (entity: T) => void;
  renderToolBar?: () => React.ReactNode[];
  renderExtraContent?: () => React.ReactNode;
  request: (params: U, sorter: any, filter: any) => Promise<RequestData<T>>;
}

const TreeTable = <T extends Record<string, any>, U extends ParamsType>({
  treeDataSource,
  removeRule,
  columns,
  treeTitle = '部门信息',
  checkTitle = '包含下级',
  searchPlaceholder = '请输入',
  renderToolBar,
  renderExtraContent,
  request,
}: TreeTableProps<T, U>) => {
  const actionRef = useRef<ActionType>(); // 用于刷新和重置 ProTable
  const [selectedRowsState, setSelectedRows] = useState<T[]>([]); // 选中行的状态
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]); // 选中的树节点
  const [checkStrictly, setcheckStrictly] = useState<boolean>(false); // 控制树节点是否严格检查
  const [treeData, setTreeData] = useState<TreeDataNode[]>(treeDataSource); // 树节点数据
  const intl = useIntl(); // 用于国际化
  const [messageApi, contextHolder] = message.useMessage(); // 用于显示消息

  useEffect(() => {
    setTreeData(treeDataSource);
  });
  // 处理树节点选中事件
  const onCheck: TreeProps['onCheck'] = (checkedKeysValue) => {
    setCheckedKeys(checkedKeysValue as React.Key[]);
    actionRef.current?.reload();
  };

  // 处理删除操作
  const handleRemove = useCallback(async () => {
    if (!selectedRowsState?.length) {
      messageApi.warning('请选择删除项');
      return;
    }
    await removeRule?.(selectedRowsState);

    setSelectedRows([]);
    actionRef.current?.reloadAndRest?.();
    messageApi.success('删除成功，即将刷新！');
  }, [removeRule, selectedRowsState]);

  // 处理复选框变化
  const checkChange: CheckboxProps['onChange'] = (e) => {
    setcheckStrictly(e.target.checked);
  };

  // 搜索树节点并进行过滤
  const searchTree = useCallback(
    debounce((value: string) => {
      if (!value) {
        setTreeData(treeDataSource);
        return;
      }
      const filterTree = (nodes: TreeDataNode[], searchText: string): TreeDataNode[] => {
        return nodes
          .map((node) => {
            const titleIncludesSearchText = node.title
              ?.toString()
              .toLowerCase()
              .includes(searchText.toLowerCase());

            if (!node.children) {
              return titleIncludesSearchText ? { ...node } : null;
            }
            const filteredChildren = filterTree(node.children, searchText);
            if (filteredChildren.length > 0 || titleIncludesSearchText) {
              return { ...node, children: filteredChildren };
            }
            return null;
          })
          .filter(Boolean) as TreeDataNode[];
      };
      setTreeData(filterTree(treeDataSource, value));
    }, 300),
    [treeDataSource],
  );

  // 处理搜索输入变化
  const searchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    searchTree(e.target.value);
  };

  // 树节点和搜索输入框的额外内容
  const defaultExtraContent = (
    <div style={{ lineHeight: 3 }}>
      <Search
        placeholder={searchPlaceholder}
        onSearch={(value) => searchTree(value)}
        onChange={searchChange}
      />
      <Checkbox onChange={checkChange}>{checkTitle}</Checkbox>
      <Tree
        checkable
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        treeData={treeData}
        checkStrictly={!checkStrictly}
        defaultExpandAll={true}
      />
    </div>
  );

  const extraContent = renderExtraContent ? renderExtraContent() : defaultExtraContent;

  return (
    <>
      {contextHolder}
      <ProCard style={{ marginBlockStart: 8 }} gutter={8} ghost>
        <ProCard title={treeTitle} colSpan="25%" style={{ height: '100%' }}>
          {extraContent}
        </ProCard>
        <ProCard>
          <ProTable<T, U>
            headerTitle={intl.formatMessage({
              id: 'pages.searchTable.title',
              defaultMessage: 'Enquiry form',
            })}
            cardBordered={true}
            rowKey="code"
            search={{ labelWidth: 120 }}
            toolBarRender={renderToolBar}
            request={request}
            columns={columns}
            rowSelection={{
              onChange: (_, selectedRows) => {
                setSelectedRows(selectedRows);
              },
            }}
            actionRef={actionRef}
          />
          {selectedRowsState?.length > 0 && (
            <FooterToolbar
              extra={
                <div>
                  <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
                  <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
                  <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
                </div>
              }
            >
              <Button loading={false} onClick={handleRemove}>
                <FormattedMessage
                  id="pages.searchTable.batchDeletion"
                  defaultMessage="Batch deletion"
                />
              </Button>
            </FooterToolbar>
          )}
        </ProCard>
      </ProCard>
    </>
  );
};

export default TreeTable;
